<script setup lang="ts">
import { addPatient, getPatientList,editPatient, delPatient } from '@/services/user';
import type { Patient,PatientList } from '@/types/user';
import { computed, onMounted, onUpdated, ref } from 'vue';
import {nameRules,idCardRules} from '@/utils/rules'
import { showConfirmDialog, showSuccessToast, showToast, type FormInstance } from 'vant';
import { useRoute, useRouter } from 'vue-router';
import { useConsultStore } from '@/stores';

// 测试账号
const testId = ref( [
  {idCard:'110101198307212600'},
  {idCard:'110101196107145504'},
  {idCard:'11010119890512132X'},
  {idCard:'110101196501023433'},
  {idCard:'110101197806108758'},
  {idCard:'110101198702171378'},
  {idCard:'110101198203195893'},
])

// 组件挂载完毕获取数据
const list  = ref<PatientList>([])

const loadList = async ()=>{
  const res =await getPatientList()
  list.value = res.data
  // 默认选择患者
  if(isChange.value && list.value.length){
    const defPatient = list.value.find(item=>item.defaultFlag ===1)
    if(defPatient) patientId.value = defPatient.id
    else patientId.value = list.value[0].id
  }
}
const resetIdFn = ()=>{
  // 重置测试账号
  testId.value.forEach((item)=>{
    list.value.forEach(patient=>{
      if(item.idCard === patient.idCard){
        testId.value.splice(testId.value.indexOf(item),1)
      }
    })
  })
  // console.log('testId',testId)
}
// 挂载状态
onMounted(()=>{
  loadList()
})
onUpdated(()=>{
  resetIdFn()
})
const options =[
  {label:'男',value:1},
  {label:'女',value:0}
]
// 是否显示popup
const show = ref(false)
const showPopup = (item?:Patient)=>{
  if(item){
    // console.log('edit')
    const {id,name,idCard,gender,defaultFlag} = item
    patient.value = {id,name,idCard,gender,defaultFlag}
  }else{
    // console.log('add')
    form.value?.resetValidation() // 重置表单校验
    patient.value = {...initPatient} // 重置数据
  }
  show.value = true
}
const initPatient:Patient={
  name:'',
  idCard: '',
  gender:1,
  defaultFlag: 0,
}
const patient = ref<Patient>({...initPatient})
// van-checkbox返回的值为boolear，手动修改
const defaultFlag = computed({
  get:()=>(patient.value.defaultFlag===1? true : false),
  set:(value)=> patient.value.defaultFlag = value ? 1 : 0
})
// 提交数据
const form =ref<FormInstance>()
const onSubmit=async()=>{
  // 表单整体校验 validate
  await form.value?.validate()
  // 校验通过后提交数据
  // console.log('校验通过')
  // 性别校验
  const gender = +patient.value.idCard.slice(-2,-1) % 2
  // console.log(gender)
  if(gender !==patient.value.gender){
    await showConfirmDialog({
      title:'温馨提示',
      message:'身份证号性别与选择的性别不一致，\n请确认是否正确？'
    })
  }
  // 提交数据 添加 或 编辑
  try{
    if(patient.value.id){
      await editPatient(patient.value)
    }else{
      // 添加患者
      await addPatient(patient.value)
    }

  }catch(e){
    console.error(e)
  }
  // 成功后，重新加载数据，成功
  show.value = false
  loadList()
  // 提示用户
  showSuccessToast(patient.value.id ? '编辑成功' : '添加成功')
}
// 删除患者
const remove = async()=>{
  if(patient.value.id){
    // 确认框，删除请求，关闭，加载，提示
    await showConfirmDialog({
      title:'温馨提示',
      message:`确认删除 ${patient.value.name} 患者吗？`
    })
    await delPatient(patient.value.id)
    loadList()
    show.value = false
    showSuccessToast('删除成功')
  }
}
// 获取链接的query参数
const route = useRoute()
const isChange = computed(()=>route.query.isChange === '1')
// 是不是选择患者
// 选择效果
const patientId = ref<string>()
const selectPatient = (item:Patient)=>{
  if(isChange.value){
    // 如果是选择患者，携带id
    patientId.value = item.id
    // 跳转到咨询页面
    // window.location.href = `/consult?patientId=${item.id}`
  }
}

// 复制身份证号
const onCopy = (id:string)=>{
  // 复制身份证号
  navigator.clipboard.writeText(id).then(()=>{
    showSuccessToast('复制成功')
  }).catch(()=>{
    showSuccessToast('复制失败，请手动复制')
  })
}
const store = useConsultStore()
const router = useRouter()
const next = ()=>{
  if(!patientId.value) return showToast('请选择患者')
  store.setPatient(patientId.value)
  // 跳转到
  router.push('/consult/pay')
}
</script>

<template>
  <div class="patient-page">
    <cp-nav-bar :title="isChange ? '选择患者' :'家庭档案'"></cp-nav-bar>
    <!-- 头部提示 -->
    <div class="patient-change" v-if="isChange">
      <h3>请选择患者信息</h3>
      <p>以便医生给出更准确的治疗，信息仅医生可见</p>
    </div>
    <div class="patient-list">
      <div v-for="item in list" :key="item.id"
      @click="selectPatient(item)"
      :class="{selected:patientId === item.id}"
      class="patient-item">
        <div class="info">
          <span class="name">{{item.name}}</span>
          <span class="id">{{item.idCard.replace(/^(.{6}).+(.{4})$/,'$1********$2')}}</span>
          <span>{{item.genderValue}}</span>
          <span>{{item.age}}岁</span>
        </div>
        <div class="icon" @click.stop="showPopup(item)"><cp-icon name="user-edit" /></div>
        <div v-if="item.defaultFlag === 1" class="tag">默认</div>
      </div>

      <div v-if="list?.length < 6" class="patient-add" @click="showPopup()">
        <cp-icon name="user-add" />
        <p>添加患者</p>
      </div>
      <div class="patient-tip">{{`最多可添加 ${6 -list.length} 人`}}</div>
    </div>
    <!-- 底部按钮 -->
    <div class="patient-next" v-if="isChange">
      <van-button @click="next" type="primary" round block>下一步</van-button>
    </div>
    <!-- 测试账号 -->
    <div class="demo" :class="{disabled:list.length > 5}">
      <div class="title">测试账号</div>
      <div class="content-id" v-for="(item) in testId" :key="item.idCard">
        <div class="left">{{item.idCard}}</div>
        <van-button @click="onCopy(item.idCard)" type="primary">复制</van-button>
      </div>
    </div>

    <!-- 使用 popup组件 -->
     <van-popup  position="right" v-model:show="show">
      <cp-nav-bar :title="patient.id?'编辑患者':'添加患者'" right-text="保存"
        @click-right="onSubmit"
      :back="()=>show =false"/>
        <van-form  autocomplete="off" ref="form">
          <van-field
          :rules="nameRules"
          v-model="patient.name" style="padding-top: 40px;" label="真实姓名" placeholder="请输入真实姓名" />
          <van-field
          :rules="idCardRules"
          v-model="patient.idCard" label="身份证号" placeholder="请输入身份证号" />
          <van-field label="性别" class="pb4">
          <!-- 单选按钮组件 -->
          <template #input>
            <cp-radio-btn v-model="patient.gender" :options="options"></cp-radio-btn>
          </template>
        </van-field>
        <van-field label="默认就诊人">
          <template #input>
            <van-checkbox v-model="defaultFlag" :icon-size="18" round />
          </template>
        </van-field>
      </van-form>
      <!-- 删除按钮 -->
      <van-action-bar v-if="patient.id">
        <van-action-bar-button text="删除"  @click="remove"/>
      </van-action-bar>
     </van-popup>
  </div>
</template>

<style lang="scss" scoped>
.patient-page {
  padding: 46px 0 80px;
  :deep() {
    .van-popup {
      width: 100%;
      height: 100%;
    }
  }
}

.patient-list {
  padding: 15px;
}
.patient-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: var(--cp-bg);
  border-radius: 8px;
  margin-bottom: 15px;
  position: relative;
  border: 1px solid var(--cp-bg);
  transition: all 0.3s;
  overflow: hidden;
  .info {
    display: flex;
    flex-wrap: wrap;
    flex: 1;
    span {
      color: var(--cp-tip);
      margin-right: 20px;
      line-height: 30px;
      &.name {
        font-size: 16px;
        color: var(--cp-text1);
        width: 80px;
        margin-right: 0;
      }
      &.id {
        color: var(--cp-text2);
        width: 180px;
      }
    }
  }
  .icon {
    color: var(--cp-tag);
    width: 20px;
    text-align: center;
  }
  .tag {
    position: absolute;
    right: 60px;
    top: 21px;
    width: 30px;
    height: 16px;
    font-size: 10px;
    color: #fff;
    background-color: var(--cp-primary);
    border-radius: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  &.selected {
    border-color: var(--cp-primary);
    background-color: var(--cp-plain);
    .icon {
      color: var(--cp-primary);
    }
  }
}
.patient-add {
  background-color: var(--cp-bg);
  color: var(--cp-primary);
  text-align: center;
  padding: 15px 0;
  border-radius: 8px;
  .cp-icon {
    font-size: 24px;
  }
}
.patient-tip {
  color: var(--cp-tag);
  padding: 12px 0;
}
.pb4 {
  padding-bottom: 4px;
}
// 底部操作栏
.van-action-bar {
  padding: 0 10px;
  margin-bottom: 10px;
  .van-button {
    color: var(--cp-price);
    background-color: var(--cp-bg);
  }
}
.demo{
  position: absolute;
  left: 0;
  bottom: 70px;
  width: 100%;
  .title{
    text-align: center;
    font-size: 16px;
  }
  .content-id{
    display: flex;
    justify-content: space-between;
    margin: 10px 20px;
    .van-button{
      width: 60px;
      height: 20px;
      font-size: 12px;
      margin-right: 10px;
    }
  }
}
.disabled{
    display: none;
  }

  .patient-change {
  padding: 15px;
  > h3 {
    font-weight: normal;
    margin-bottom: 5px;
  }
  > p {
    color: var(--cp-text3);
  }
}
.patient-next {
  padding: 15px;
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 80px;
  box-sizing: border-box;
}

</style>
